# coding: utf-8
"""
Forms and validation code for user registration.

"""


from django.contrib.auth.models import User
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _


# I put this on all required fields, because it's easier to pick up
# on them with CSS or JavaScript if they have a class of "required"
# in the HTML. Your mileage may vary. If/when Django ticket #3515
# lands in trunk, this will no longer be necessary.
attrs_dict = { 'class': 'required' }


class RegistrationForm(forms.Form):
    """
    Form for registering a new user account.
    
    Validates that the requested username is not already in use, and
    requires the password to be entered twice to catch typos.
    
    Subclasses should feel free to add any additional validation they
    need, but should avoid defining a ``save()`` method -- the actual
    saving of collected user data is delegated to the active
    registration backend.
    
    """
    username = forms.RegexField(regex=r'^\w+$',
                                max_length=30,
                                widget=forms.TextInput(attrs=attrs_dict),
                                label=_("Usuario"),
                                error_messages={ 'invalid': _("Solo se pueden utilizar letras, numeros y \"_\".") })
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
                                                               maxlength=75)),
                             label=_("E-mail"))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                                label=_(u"Contraseña"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                                label=_(u"Contraseña (otra vez)"))
    
    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.
        
        """
        try:
            user = User.objects.get(username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(_("Ya existe un usuario con ese nombre."))

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.
        
        """
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("Las contrasenas no coinciden."))
        return self.cleaned_data


class RegistrationFormTermsOfService(RegistrationForm):
    """
    Subclass of ``RegistrationForm`` which adds a required checkbox
    for agreeing to a site's Terms of Service.
    
    """
    tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
                             label=_(u'He leido los Terminos de Servicio y estoy de acuerdo'),
                             error_messages={ 'required': _("Debes de aceptar los Terminos para poder registrarte") })


class RegistrationFormUniqueEmail(RegistrationForm):
    """
    Subclass of ``RegistrationForm`` which enforces uniqueness of
    email addresses.
    
    """
    def clean_email(self):
        """
        Validate that the supplied email address is unique for the
        site.
        
        """
        if User.objects.filter(email__iexact=self.cleaned_data['email']):
            raise forms.ValidationError(_("Este correo ya se encuentra en uso. Por favor utiliza uno diferente."))
        return self.cleaned_data['email']

class UserProfileForm(forms.Form):
    messages={ 'required': "Este campo es requerido!" }
    is_uploader = forms.BooleanField(label="Uploader",
                                     required =False,
                                     error_messages= { 'invalid': "Este campo es invalido!" })
    logo = forms.ImageField(label=("Logo o imagen"),
                            required =False)
    company = forms.CharField(max_length=75,
                                label=("Empresa"),
                                error_messages= messages)
    phone = forms.CharField(max_length=15,
                                label=("Telefono"),
                                error_messages= messages)
    comments = forms.CharField(widget = forms.Textarea, max_length=200,
                                label=("Comentarios"),
                                help_text=(u"Ej. Temática de los comics, objetivo de la empresa, etc..."),
                                required =False)
    website = forms.URLField(max_length=200,
                                label=("Web"),
                                help_text=(u"Link si ya tienes otra pag web"),
                                required =False)